<template>
  <view class="address-page">
    <!-- 自定义导航栏 -->
  
    <!-- 地址列表 -->
    <scroll-view class="address-list" scroll-y>
      <!-- 地址卡片 -->
      <u-swipe-action
        v-for="(item, index) in addressList"
        :key="item.id"
        :index="index"
        :options="swipeOptions"
        @click="handleSwipeClick"
      >
        <view style="padding: 25rpx;">
			<view class="address-card" @click="selectAddress(item)">
			  <view class="card-header">
			    <text class="name">{{item.name}}</text>
			    <text class="phone">{{item.phone}}</text>
			    <u-tag
			      v-if="item.isDefault"
			      text="默认"
			      size="mini"
			      type="error"
			      shape="circle"
			    ></u-tag>
			  </view>
			  <view class="card-body">
			    <u-icon name="map" size="18" color="#606266"></u-icon>
			    <text class="address-text">
			      {{item.province}}{{item.city}}{{item.district}}{{item.detail}}
			    </text>
			  </view>
			  <view class="card-footer">
			    <u-icon  name="edit-pen" size="20" color="#909399" @click.stop="editAddress(item)"></u-icon>
				<text style="margin-left: 30rpx;"></text>
				<u-icon  name="trash-fill" size="20" color="#ff0000" @click.stop="delAddress(item,index)"></u-icon>
			  </view>
			
			</view>
		</view>
      </u-swipe-action>
      
      <!-- 空状态 -->
      <u-empty
        v-if="addressList.length === 0"
        mode="address"
        icon="http://cdn.uviewui.com/uview/empty/address.png"
        text="您还没有添加地址哦~"
        marginTop="100"
      ></u-empty>
    </scroll-view>
    
    <!-- 新增地址按钮 -->
    <view class="add-btn-wrapper">
      <u-button
        type="error"
        shape="circle"
        text="+ 新增地址"
        @click="addAddress"
      ></u-button>
    </view>
    
    <!-- 地址编辑弹窗 -->
    <u-popup
      :show="showPopup"
      mode="bottom"
      round="16"
      closeable
      @close="closePopup"
    >
      <view class="popup-content">
        <view class="popup-header">
          <text class="title">{{isEdit ? '编辑地址' : '新增地址'}}</text>
        </view>
        
        <u--form
          labelPosition="left"
          :model="formData"
          :rules="rules"
		  labelWidth="150rpx"
          ref="addressForm"
        >
          <u-form-item
            label="收货人"
            prop="name"
            borderBottom
          >
            <u--input
              v-model="formData.name"
              placeholder="请输入收货人姓名"
              border="none"
            ></u--input>
          </u-form-item>
          
          <u-form-item
            label="联系电话"
            prop="phone"
            borderBottom
          >
            <u--input
              v-model="formData.phone"
              placeholder="请输入收货人手机号"
              border="none"
              type="number"
            ></u--input>
          </u-form-item>
          
          <u-form-item
            label="所在地区"
            prop="region"
            borderBottom
            @click="showRegionPicker"
          >
            <u--input
              v-model="regionText"
              placeholder="请选择省市区"
              border="none"
              disabled
              disabledColor="#ffffff"
            ></u--input>
            <u-icon
              slot="right"
              name="arrow-right"
            ></u-icon>
          </u-form-item>
          
          <u-form-item
            label="详细地址"
            prop="detail"
            borderBottom
          >
            <u--input
              v-model="formData.detail"
              placeholder="请输入详细地址（如街道、门牌号等）"
              border="none"
            ></u--input>
          </u-form-item>
          
          <u-form-item
            label="设为默认地址"
            borderBottom
			labelWidth="250rpx"
          >
            <u-switch
              v-model="formData.isDefault"
              activeColor="#fa436a"
            ></u-switch>
          </u-form-item>
        </u--form>
        
        <view class="popup-footer">
          <u-button
            type="error"
            shape="circle"
            text="保存地址"
            @click="confirmAddress"
          ></u-button>
        </view>
      </view>
    </u-popup>
    
    <!-- 省市区选择器 -->
    <u-picker
      :show="showPicker"
      :columns="regionColumns"
      keyName="label"
      @confirm="regionConfirm"
      @cancel="showPicker = false"
    ></u-picker>
  </view>
</template>

<script>
import regionData from '@/common/region-data.js'
export default {
  data() {
    return {
      selectMode: false, // 是否选择地址模式
      showPopup: false,
      showPicker: false,
      isEdit: false,
      currentId: null,
      swipeOptions: [
        {
          text: '删除',
          style: {
            backgroundColor: '#fa436a'
          }
        }
      ],
      formData: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      },
      rules: {
        name: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              return /^1[3-9]\d{9}$/.test(value);
            }, 
            message: '手机号码格式不正确', 
            trigger: 'blur' 
          }
        ],
        region: [
          { required: true, message: '请选择所在地区', trigger: 'change' }
        ],
        detail: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      },
      regionColumns: [[],[],[] ],
	  regionData: regionData,
      addressList: [
        {
          id: 1,
          name: '张三',
          phone: '13800138000',
          province: '广东省',
          city: '深圳市',
          district: '南山区',
          detail: '科技园路123号',
          isDefault: true
        },
        {
          id: 2,
          name: '李四',
          phone: '13900139000',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          detail: '建国路88号',
          isDefault: false
        }
      ]
    }
  },
  computed: {
    regionText() {
      if (this.formData.province && this.formData.city && this.formData.district) {
        return `${this.formData.province} ${this.formData.city} ${this.formData.district}`
      }
      return ''
    }
  },
  onLoad(options) {
    if (options.selectMode === 'true') {
      this.selectMode = true
    }
	console.log('regionData',regionData)
	regionData.forEach((item) => {
		this.regionColumns[0].push({
			label: item.label,
			value: item.value
		})
		item.children.forEach((item1) => {
			this.regionColumns[1].push({
				label: item1.label,
				value: item1.value
			})
			item1.children.forEach((item2) => {
				this.regionColumns[2].push({
					label: item2.label,
					value: item2.value
				})
			})
		})
	})
	
  },
  methods: {
    // 显示省市区选择器
    showRegionPicker() {
      this.showPicker = true
    },
    // 省市区选择确认
    regionConfirm(e) {
      const { value } = e
      this.formData.province = value[0].label
      this.formData.city = value[1].label
      this.formData.district = value[2].label
      this.showPicker = false
    },
    // 新增地址
    addAddress() {
      this.isEdit = false
      this.resetForm()
      this.showPopup = true
    },
	//删除地址
	delAddress(item,index){
		uni.showModal({
			title:'温馨提示',
			content:'是否删除该地址？',
			success: (red) => {
				if(red.confirm){
					uni.showToast({
						icon:'none',
						title:'删除成功'
					})
					this.addressList.splice(index,1)
				}
			}
		})
	},
    // 编辑地址
    editAddress(item) {
      this.isEdit = true
      this.currentId = item.id
      this.formData = {
        name: item.name,
        phone: item.phone,
        province: item.province,
        city: item.city,
        district: item.district,
        detail: item.detail,
        isDefault: item.isDefault
      }
      this.showPopup = true
    },
    // 侧滑删除
    handleSwipeClick(index) {
      this.deleteAddress(this.addressList[index].id, index)
    },
    // 删除地址
    deleteAddress(id, index) {
      this.$refs.uToast.show({
        type: 'default',
        position: 'center',
        title: '确定删除该地址吗？',
        icon: false,
        duration: 0,
        params: { id, index },
        buttons: [
          {
            text: '取消',
            color: '#333',
            type: 'default'
          },
          {
            text: '确定',
            color: '#fa436a',
            type: 'error',
            click: () => {
              this.addressList.splice(index, 1)
              this.$refs.uToast.hide()
              uni.$u.toast('删除成功')
            }
          }
        ]
      })
    },
	 // 省变化时加载市数据
	  onProvinceChange(e) {
	    const provinceIndex = e.detail.value[0]
	    const cities = this.regionData[provinceIndex].children
	    
	    this.regionColumns[1] = cities.map(city => {
	      return {
	        label: city.label,
	        value: city.value
	      }
	    })
	    
	    // 重置区数据
	    this.regionColumns[2] = []
	  },
	  
	  // 市变化时加载区数据
	  onCityChange(e) {
	    const provinceIndex = e.detail.value[0]
	    const cityIndex = e.detail.value[1]
	    const districts = this.regionData[provinceIndex].children[cityIndex].children
	    
	    this.regionColumns[2] = districts.map(district => {
	      return {
	        label: district.label,
	        value: district.value
	      }
	    })
	  },
    // 选择地址（选择模式）
    selectAddress(item) {
      if (!this.selectMode) return
      
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      prevPage.$vm.selectedAddress = item
      uni.navigateBack()
    },
    // 重置表单
    resetForm() {
      this.formData = {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      }
      this.$refs.addressForm.resetFields()
    },
    // 关闭弹窗
    closePopup() {
      this.showPopup = false
    },
    // 确认保存地址
    async confirmAddress() {
      try {
        await this.$refs.addressForm.validate()
        
        const addressData = {
          ...this.formData,
          id: this.isEdit ? this.currentId : uni.$u.guid()
        }
        
        uni.showLoading({
          title: '保存中...'
        })
        
        // 模拟API请求
        setTimeout(() => {
          uni.hideLoading()
          
          if (this.isEdit) {
            const index = this.addressList.findIndex(item => item.id === this.currentId)
            if (index !== -1) {
              this.addressList.splice(index, 1, addressData)
            }
          } else {
            this.addressList.unshift(addressData)
          }
          
          // 如果设置为默认地址，其他地址取消默认
          if (addressData.isDefault) {
            this.addressList.forEach(item => {
              if (item.id !== addressData.id) {
                item.isDefault = false
              }
            })
          }
          
          this.closePopup()
          uni.$u.toast('保存成功')
        }, 800)
      } catch (e) {
        console.log('验证失败', e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.address-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
}

.address-list {
  flex: 1;
  
  .address-card {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 24rpx;
    
    .card-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .name {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .phone {
        font-size: 28rpx;
        color: $u-content-color;
        margin-left: 30rpx;
      }
    }
    
    .card-body {
      display: flex;
      align-items: flex-start;
      margin-bottom: 20rpx;
      
      .address-text {
        font-size: 28rpx;
        color: $u-content-color;
        line-height: 1.5;
        margin-left: 10rpx;
      }
    }
    
    .card-footer {
      display: flex;
      justify-content: flex-end;
      padding-top: 20rpx;
      border-top: 1rpx solid $u-border-color;
    }
  }
}

.add-btn-wrapper {
  padding: 20rpx;
  background-color: #fff;
  
  ::v-deep .u-button {
    height: 80rpx;
  }
}

.popup-content {
  padding: 30rpx;
  
  .popup-header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      text-align: center;
    }
  }
  
  .popup-footer {
    margin-top: 40rpx;
    
    ::v-deep .u-button {
      height: 80rpx;
    }
  }
}
</style>